﻿@model GameWeb.Models.GameModel

@{
    ViewBag.Title = "Play";
}

<script src="@Url.Content("~/JSLINQ.js")" type="text/javascript"></script>

<canvas id="boardCanvas" width="800" height="600">

</canvas>
<br />

<table>
<tr>
<td><canvas id="pieceCanvas" width="360" height="60"></canvas></td>
<td>
<table>
<tr>
	<td><input type="button" value="Send Move" id="btnSendMove" class="moveButton"/></td>
</tr>
<tr>
	<td><input type="button" value="Recall" id="btnRecall" class="moveButton"/></td>
</tr>
</table>
</td>
<td>
    <table>
        @foreach (var user in Model.PlayerNames) { 
            <tr>
                <td style="background-color:@(user.PlayerName == Model.CurrentTurnUser ? "red" : "white")">@user.PlayerName</td>
                <td>@user.Score</td>
            </tr>
        }
    </table>
</td>
<td>
    <table>
        <tr>
            <td><input id="btnRefresh" type="button" value="Refresh" /></td>
        </tr>
        <tr>
            <td>
                <table>
                    <tr>
                        <td><input type="button" id="btnPrevMove" value="&lt;" /></td>
                        <td>Moves</td>
                        <td><input type="button" id="btnNextMove" value="&gt;" /></td>
                    </tr>
                </table>
                <input type="button" id="btnShowLast" value="Backout Move" />
            </td>
        </tr>
    </table>
 </td>
 <td>
    <table>
        <tr><td>Remaining Pieces&nbsp;@Model.RemainingPieces</td></tr>
    </table>
 </td>
</tr>

</table>

@Html.Hidden("baseSquareWidth", Model.BaseSquareWidth)
@Html.Hidden("baseSquareHeight", Model.BaseSquareHeight)
@Html.Hidden("boardWidth", Model.BoardWidth)
@Html.Hidden("boardHeight", Model.BoardHeight)

@Html.Hidden("trayPieces", Model.TrayPiecesJson)
@Html.Hidden("BoardPiecesJson", Model.BoardPiecesJson)

@Html.Hidden("MatchPlayerTurnId", Model.MatchPlayerTurnId)
@Html.Hidden("UserName", Model.CurrentUser)
@Html.Hidden("CurrentTurnUser", Model.CurrentTurnUser)
@Html.Hidden("GameId", Model.GameId)

@Html.HiddenFor(mod => mod.PlayerMovesJson)

<script type="text/javascript">

    var scale = 1.00;

    var boardCanvasCtx, pieceCanvasCtx;
    var baseSquareWidth;
    var baseSquareHeight;

    var boardHeight, boardWidth;

    var colors = ["#FF1A00", "#1A50FF", "#FF66FF", "#FFFF66", "#75EB00", "#EB7500"];

    Game = {
        curHistoryMove: null,
        drawGrid: true,
        offBoardPos: null,
        playerPieceCount: 6,
        DrawPipRect: function (ctx, pipAreaRect, pipDim) {
            ctx.fillRect(pipAreaRect.startCoord.x + (pipAreaRect.size.x / 2 - pipDim.x / 2),
			pipAreaRect.startCoord.y + (pipAreaRect.size.y / 2 - pipDim.y / 2), pipDim.x, pipDim.y);
        },

        DrawPieceRect: function (ctx, pieceRect, ColorIndex, ShapeIndex) {
            Game.DrawPiece(ctx, pieceRect.startCoord.x, pieceRect.startCoord.y, pieceRect.size.x, pieceRect.size.y, ColorIndex, ShapeIndex);
        },

        areMoveButtonsDisabled: function () {
            var curUser = $('#UserName').val();
            var curUserTurn = $('#CurrentTurnUser').val();
            return curUser != curUserTurn;
        },

        DrawBorder: function (ctx, style, x, y, width, height) {
            ctx.strokeStyle = style;
            ctx.strokeRect(x, y, width, height);
        },

        DrawPiece: function (ctx, x, y, width, height, ColorIndex, ShapeIndex) {
            ctx.fillStyle = colors[ColorIndex];
            ctx.fillRect(x, y, width, height);

            //draw pips
            var pipDim = new Game.Coord(width / 8, height / 8);
            ctx.fillStyle = "#000";
            switch (ShapeIndex) {
                case 0:
                    ctx.fillRect(x + (width / 2 - pipDim.x / 2), y + (height / 2 - pipDim.y / 2), pipDim.x, pipDim.y);
                    break;
                case 1:
                    var topRight = new Game.Rect(new Game.Coord(x + (width / 2), y), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, topRight, pipDim);
                    var bottomLeft = new Game.Rect(new Game.Coord(x, y + height / 2), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, bottomLeft, pipDim);
                    break;
                case 2:
                    ctx.fillRect(x + (width / 2 - pipDim.x / 2), y + (height / 2 - pipDim.y / 2), pipDim.x, pipDim.y);
                    var topRight = new Game.Rect(new Game.Coord(x + (width / 2), y), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, topRight, pipDim);
                    var bottomLeft = new Game.Rect(new Game.Coord(x, y + height / 2), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, bottomLeft, pipDim);
                    break;
                case 3:
                    var topRight = new Game.Rect(new Game.Coord(x + (width / 2), y), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, topRight, pipDim);
                    var bottomLeft = new Game.Rect(new Game.Coord(x, y + height / 2), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, bottomLeft, pipDim);
                    var topLeft = new Game.Rect(new Game.Coord(x, y), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, topLeft, pipDim);
                    var bottomRight = new Game.Rect(new Game.Coord(x + (width / 2), y + height / 2), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, bottomRight, pipDim);
                    break;
                case 4:
                    ctx.fillRect(x + (width / 2 - pipDim.x / 2), y + (height / 2 - pipDim.y / 2), pipDim.x, pipDim.y);
                    var topRight = new Game.Rect(new Game.Coord(x + (width / 2), y), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, topRight, pipDim);
                    var bottomLeft = new Game.Rect(new Game.Coord(x, y + height / 2), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, bottomLeft, pipDim);
                    var topLeft = new Game.Rect(new Game.Coord(x, y), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, topLeft, pipDim);
                    var bottomRight = new Game.Rect(new Game.Coord(x + (width / 2), y + height / 2), new Game.Coord(width / 2, height / 2));
                    Game.DrawPipRect(ctx, bottomRight, pipDim);
                    break;
                case 5:
                    var topLeftSixth = new Game.Rect(new Game.Coord(x, y), new Game.Coord(width / 3, height / 2));
                    Game.DrawPipRect(ctx, topLeftSixth, pipDim);
                    var topMiddleSixth = new Game.Rect(new Game.Coord(x + width / 3, y), new Game.Coord(width / 3, height / 2));
                    Game.DrawPipRect(ctx, topMiddleSixth, pipDim);
                    var topRightSixth = new Game.Rect(new Game.Coord(x + (width / 3) * 2, y), new Game.Coord(width / 3, height / 2));
                    Game.DrawPipRect(ctx, topRightSixth, pipDim);
                    var bottomLeftSixth = new Game.Rect(new Game.Coord(x, y + height / 2), new Game.Coord(width / 3, height / 2));
                    Game.DrawPipRect(ctx, bottomLeftSixth, pipDim);
                    var bottomMiddleSixth = new Game.Rect(new Game.Coord(x + (width / 3), y + height / 2), new Game.Coord(width / 3, height / 2));
                    Game.DrawPipRect(ctx, bottomMiddleSixth, pipDim);
                    var bottomRightSixth = new Game.Rect(new Game.Coord(x + (width / 3) * 2, y + height / 2), new Game.Coord(width / 3, height / 2));
                    Game.DrawPipRect(ctx, bottomRightSixth, pipDim);
                    break;
            }
        }
    };
    Game.Tray = {
        pieceSelectedIndex: -1,
        pieceWidth: 40,
        pieceHeight: 40,
        pieceRects: [],
        pieceJson: {},
        drawTrayPieces: function (ctx) {
            var pieceCanvasHeight = $('#pieceCanvas').height();
            var pieceCanvasWidth = $('#pieceCanvas').width();
            ctx.fillStyle = "#C0C0C0";
            ctx.fillRect(0, 0, pieceCanvasWidth, pieceCanvasHeight);
            Game.Tray.pieceRects.length = 0;
            var startx = 10;
            for (var curX = 0; curX < Game.Tray.pieceJson.length; curX++) {
                Game.Tray.pieceRects.push(new Game.Rect(new Game.Coord(startx + curX * 60, 10), new Game.Coord(Game.Tray.pieceWidth, Game.Tray.pieceHeight)));
                if (Game.Tray.pieceJson[curX].BoardXpos == Game.offBoardPos && Game.Tray.pieceJson[curX].BoardYpos == Game.offBoardPos)
                    Game.DrawPieceRect(ctx, Game.Tray.pieceRects[curX], Game.Tray.pieceJson[curX].ColorIndex, Game.Tray.pieceJson[curX].ShapeIndex);
            }
        },
        piecesOnBoard: function () {
            return JSLINQ(Game.Tray.pieceJson).Where(function (item) { return item.BoardXpos != Game.offBoardPos && item.BoardYpos != Game.offBoardPos; }).items;
        },
        recallPiece: function (piece) {
            var xpos = piece.BoardXpos + Game.Board.OffsetFromScreenOrigin.x;
            var ypos = piece.BoardYpos + Game.Board.OffsetFromScreenOrigin.y;
            piece.BoardXpos = Game.offBoardPos;
            piece.BoardYpos = Game.offBoardPos;
            Game.Tray.drawTrayPieces(pieceCanvasCtx);
            boardCanvasCtx.fillStyle = "#C8C8C8";
            boardCanvasCtx.fillRect(xpos * (baseSquareWidth * scale), ypos * (baseSquareHeight * scale), baseSquareWidth * scale, baseSquareHeight * scale);

            //draw border
            if (Game.drawGrid)
                boardCanvasCtx.strokeRect(xpos * (baseSquareWidth * scale), ypos * (baseSquareHeight * scale), baseSquareWidth * scale, baseSquareHeight * scale);
        }
    };
    Game.Coord = function (x, y) {
        this.x = x;
        this.y = y;
    };
    Game.Rect = function (coord, size) {
        this.startCoord = coord;
        this.size = size;
        this.endCoord = function () {
            return new Game.Coord(this.startCoord.x + this.size.x, this.startCoord.y + this.size.y);
        }
        this.hitTest = function (coord) {
            if (coord.x > this.startCoord.x && coord.y > this.startCoord.y &&
				coord.x < this.endCoord().x && coord.y < this.endCoord().y)
                return true;
            return false;
        };
        this.drawRectBorder = function (ctx, color) {
            ctx.strokeStyle = color;
            ctx.lineboardWidth = 2;

            ctx.strokeRect(this.startCoord.x - 5, this.startCoord.y - 5, this.size.x + 10, this.size.y + 10);
        };
    };

    //dummy struct. will come from server.
    Game.Board = {
        BoardSquareCount: { width: 100, height: 100 },
        OffsetFromScreenOrigin: { x: 0, y: 0 },
        //Pieces: [{ ColorIndex: 2, ShapeIndex: 1, BoardXpos: 0, BoardYpos: 0 }, { ColorIndex: 2, ShapeIndex: 2, BoardXpos: -1, BoardYpos: 0}]
        Pieces: [],
        HistoryMoves: null,
        showHistoryMove: function (nextNdxFunc) {
            $.each(Game.Board.HistoryMoves[Game.curHistoryMove].Moves, function (ndx, histElem) {
                var historyPiece = histElem;
                $.each(Game.Board.Pieces, function (ndx, elem) {
                    if (elem.BoardXpos != Game.offBoardPos && elem.BoardYpos != Game.offBoardPos) {
                        //var bxPos = new Game.Coord(Game.Board.OffsetFromScreenOrigin.x + elem.BoardXpos, Game.Board.OffsetFromScreenOrigin.y + elem.BoardYpos);
                        if (elem.BoardXpos === historyPiece.BoardXPos && elem.BoardYpos === historyPiece.BoardYPos) {
                            Game.DrawBorder(boardCanvasCtx, '#999', elem.BoardXpos * (baseSquareWidth * scale), elem.BoardYpos * (baseSquareHeight * scale),
			                    baseSquareWidth * scale, baseSquareHeight * scale);
                            Game.DrawPiece(boardCanvasCtx, elem.BoardXpos * (baseSquareWidth * scale), elem.BoardYpos * (baseSquareHeight * scale),
			                    baseSquareWidth * scale, baseSquareHeight * scale, elem.ColorIndex, elem.ShapeIndex);
                            return false;
                        }
                    }
                });
            });
            nextNdxFunc();

            $.each(Game.Board.HistoryMoves[Game.curHistoryMove].Moves, function (ndx, elem) {
                Game.DrawBorder(boardCanvasCtx, '#000', elem.BoardXPos * (baseSquareWidth * scale), elem.BoardYPos * (baseSquareHeight * scale),
			baseSquareWidth * scale, baseSquareHeight * scale);
            });
        }
    }

    $(document).ready(function () {
        var c = document.getElementById("boardCanvas");
        baseSquareWidth = $('#baseSquareWidth').val();
        baseSquareHeight = $('#baseSquareHeight').val();

        Game.Board.Pieces = $.parseJSON($('#BoardPiecesJson').val());

        //$('#boardCanvas').width($('#boardWidth').val());
        //$('#boardCanvas').height($('#boardHeight').val());
        boardCanvasCtx = c.getContext("2d");
        var p = document.getElementById("pieceCanvas");
        pieceCanvasCtx = p.getContext("2d");

        boardCanvasCtx.fillStyle = "#C8C8C8";
        boardHeight = $('#boardCanvas').height();
        boardWidth = $('#boardCanvas').width();
        boardCanvasCtx.fillRect(0, 0, boardWidth * scale, boardHeight * scale);

        boardCanvasCtx.strokeStyle = '#999';
        boardCanvasCtx.lineboardWidth = 1;
        var hNdx, vNdx;
        if (Game.drawGrid) {
            for (hNdx = (baseSquareHeight * scale); hNdx < boardHeight * scale; hNdx += (baseSquareHeight * scale)) {
                //ctx.beginPath();
                boardCanvasCtx.moveTo(0, hNdx);
                boardCanvasCtx.lineTo(boardWidth * scale, hNdx);
                boardCanvasCtx.closePath();
                boardCanvasCtx.stroke();
            }
            for (vNdx = (baseSquareWidth * scale); vNdx < boardWidth * scale; vNdx += (baseSquareWidth * scale)) {
                //ctx.beginPath();
                boardCanvasCtx.moveTo(vNdx, 0);
                boardCanvasCtx.lineTo(vNdx, boardHeight * scale);
                boardCanvasCtx.closePath();
                boardCanvasCtx.stroke();
            }
        }
        //setup dummy player tray pieces, overridden by code below
        //Game.Tray.pieceJson = [{ ColorIndex: 0, ShapeIndex: 0, BoardXpos: null, BoardYpos: null }, { ColorIndex: 1, ShapeIndex: 1, BoardXpos: null, BoardYpos: null },
        //	{ ColorIndex: 2, ShapeIndex: 2, BoardXpos: null, BoardYpos: null }, { ColorIndex: 3, ShapeIndex: 3, BoardXpos: null, BoardYpos: null },
        //	{ ColorIndex: 4, ShapeIndex: 4, BoardXpos: null, BoardYpos: null }, { ColorIndex: 5, ShapeIndex: 5, BoardXpos: null, BoardYpos: null}];

        var trayPieceJson = $('#trayPieces').val();
        Game.Tray.pieceJson = $.parseJSON(trayPieceJson);
        Game.Tray.drawTrayPieces(pieceCanvasCtx);

        $("#pieceCanvas").click(function (e) {
            //Game.Tray.drawTrayPieces(pieceCanvasCtx);
            var pieceSel = -1;
            for (var curX = 0; curX < Game.playerPieceCount; curX++) {
                if (Game.Tray.pieceRects[curX].hitTest(new Game.Coord(e.pageX - $("#pieceCanvas").offset().left,
						e.pageY - $("#pieceCanvas").offset().top))) {
                    pieceSel = curX;
                    break;
                }
            }
            if (pieceSel != -1) {
                if (pieceSel != Game.Tray.pieceSelectedIndex) {
                    Game.Tray.pieceSelectedIndex = pieceSel;
                    Game.Tray.pieceRects[pieceSel].drawRectBorder(pieceCanvasCtx, "FF0000");
                } else {
                    Game.Tray.pieceSelectedIndex = -1;
                    Game.Tray.drawTrayPieces(pieceCanvasCtx);
                }
            }
        });

        $('#boardCanvas').click(function (e) {
            var clickPos = new Game.Coord(e.pageX - $("#boardCanvas").offset().left,
						e.pageY - $("#boardCanvas").offset().top);
            var xpos = Math.floor(clickPos.x / (baseSquareWidth * scale));
            var ypos = Math.floor(clickPos.y / (baseSquareHeight * scale));

            var alreadyPieceInPosition = false;
            $.each(Game.Board.Pieces, function (ndx, elem) {
                var bxPos = new Game.Coord(Game.Board.OffsetFromScreenOrigin.x + elem.BoardXpos, Game.Board.OffsetFromScreenOrigin.y + elem.BoardYpos);
                if (bxPos.x === xpos && bxPos.y === ypos) {
                    alreadyPieceInPosition = true;
                    return;
                }
            });

            if (alreadyPieceInPosition)
                return;

            var pieceFromThisTurn = -1;
            //check to see if this is a piece the user has already placed this turn
            $.each(Game.Tray.pieceJson, function (ndx, elem) {
                if (elem.BoardXpos != Game.offBoardPos && elem.BoardYpos != Game.offBoardPos) {
                    var bxPos = new Game.Coord(Game.Board.OffsetFromScreenOrigin.x + elem.BoardXpos, Game.Board.OffsetFromScreenOrigin.y + elem.BoardYpos);
                    if (bxPos.x === xpos && bxPos.y === ypos) {
                        pieceFromThisTurn = ndx;
                        return;
                    }
                }
            });

            //save current sel piece in case recall below overwrites it
            var pieceSelBackup = Game.Tray.pieceSelectedIndex;
            if (pieceFromThisTurn != -1) {
                Game.Tray.recallPiece(Game.Tray.pieceJson[pieceFromThisTurn]);
                Game.Tray.pieceSelectedIndex = pieceFromThisTurn;
                Game.Tray.pieceRects[pieceFromThisTurn].drawRectBorder(pieceCanvasCtx, "FF0000");
            }
            if (pieceSelBackup >= 0 && pieceSelBackup != pieceFromThisTurn) {
                Game.DrawPiece(boardCanvasCtx, xpos * (baseSquareWidth * scale), ypos * (baseSquareHeight * scale),
				    baseSquareWidth * scale, baseSquareHeight * scale,
                    Game.Tray.pieceJson[pieceSelBackup].ColorIndex,
				    Game.Tray.pieceJson[pieceSelBackup].ShapeIndex);
                Game.Tray.pieceJson[pieceSelBackup].BoardXpos = xpos - Game.Board.OffsetFromScreenOrigin.x;
                Game.Tray.pieceJson[pieceSelBackup].BoardYpos = ypos - Game.Board.OffsetFromScreenOrigin.y;
                Game.Tray.pieceSelectedIndex = -1;
                Game.Tray.drawTrayPieces(pieceCanvasCtx);
            }

            $('input.moveButton').attr('disabled', Game.areMoveButtonsDisabled());
        });

        $.each(Game.Board.Pieces, function (ndx, elem) {
            var bxPos = new Game.Coord(Game.Board.OffsetFromScreenOrigin.x + elem.BoardXpos, Game.Board.OffsetFromScreenOrigin.y + elem.BoardYpos);
            Game.DrawPiece(boardCanvasCtx, bxPos.x * (baseSquareWidth * scale), bxPos.y * (baseSquareHeight * scale),
			baseSquareWidth * scale, baseSquareHeight * scale, elem.ColorIndex, elem.ShapeIndex);
        });

        var moveDisable = Game.areMoveButtonsDisabled();
        $('input.moveButton').attr('disabled', moveDisable);

        $('#btnRecall').click(function () {
            $.each(Game.Tray.piecesOnBoard(), function (ndx, elem) {
                if (elem.BoardXpos != Game.offBoardPos && elem.BoardYpos != Game.offBoardPos) {
                    Game.Tray.recallPiece(elem);
                }
            });
            $('input.moveButton').attr('disabled', Game.areMoveButtonsDisabled());
        });

        $('#btnRefresh').click(function () {
            var gameId = $('#GameId').val();
            window.location.href = "/Game/Play/" + gameId;
        });

        $('#btnSendMove').click(function () {
            if (Game.Tray.piecesOnBoard().length === 0) {
                if (!confirm("No pieces have been moved. Are you sure you want to skip your turn?"))
                    return;
            }
            var gameId = $('#GameId').val();
            var moveData = {};
            moveData.gameId = gameId;
            moveData.pieces = Game.Tray.pieceJson;
            //pieces.pieces = $.toJSON(Game.Tray.piecesOnBoard());
            $.ajax({
                url: '/Game/Move',
                data: $.toJSON(moveData),
                type: 'POST',
                async: false,
                contentType: 'application/json',
                dataType: "json",
                success: function (response) {
                    if (response != "")
                        alert(response);
                    window.location.href = "/Game/Play/" + gameId;
                },
                error: function (response) {
                    alert("post error");
                }
            });
        });

        $('#btnNextMove').attr('disabled', 'true');
        //$('#btnPrevMove').attr('disabled', 'false');

        $('#btnNextMove').click(function () {
            if (Game.curHistoryMove == Game.Board.HistoryMoves.length - 1)
                return;
            Game.Board.showHistoryMove(function () { Game.curHistoryMove++; });
            if (Game.curHistoryMove == Game.Board.HistoryMoves.length - 1)
                $('#btnNextMove').attr('disabled', 'true');
            $('#btnPrevMove').removeAttr('disabled');
        });

        $('#btnPrevMove').click(function () {
            if (Game.curHistoryMove == 0)
                return;
            Game.Board.showHistoryMove(function () { Game.curHistoryMove--; });
            if (Game.curHistoryMove == 0)
                $('#btnPrevMove').attr('disabled', 'true');
            $('#btnNextMove').removeAttr('disabled');
        });

        var playerMoves = $('#PlayerMovesJson').val();
        Game.Board.HistoryMoves = $.parseJSON(playerMoves);
        Game.curHistoryMove = Game.Board.HistoryMoves.length - 1;
        $.each(Game.Board.HistoryMoves[Game.curHistoryMove].Moves, function (ndx, elem) {
            Game.DrawBorder(boardCanvasCtx, '#000', elem.BoardXPos * (baseSquareWidth * scale), elem.BoardYPos * (baseSquareHeight * scale),
			baseSquareWidth * scale, baseSquareHeight * scale);
        });

        var xx = 5;

        //        $('#btnUndo').click(function () {
        //            if (!confirm("Are you sure you want to undo the last move?"))
        //                return;
        //            var gameId = $('#GameId').val();
        //            $.ajax({
        //                url: '/Game/BackoutLastTurn/' + gameId,
        //                data: {},
        //                type: 'POST',
        //                contentType: 'application/json',
        //                dataType: "json",
        //                success: function (response) {
        //                    window.location.href = "/Game/Play/" + gameId;
        //                },
        //                error: function (response) {
        //                    alert("post error");
        //                }
        //            });
        //        });
    });

</script>
